global.Kuo_MysqlTABLE ={
    TABLE:{}, //默认字段
    TaBle:{} //默认插入值
};
var Kuo_Mysql = (function(){
    let Kuo_Mysql_ =  {
        ShiWuBiao:"@@@@@@",
        Where_:null, //where 条件组合
        Order_:null, //排序组合
        Table_:null, //选择的表
        Limit_:null, //查询条数
        Zhicha_:null, //只查询
        Shiwu_:false, //开启事务
      
        TABLE:{}, //默认字段
        TaBle:{}, //默认插入值
        Config:async (config)=>{
           
            return Kuo_Mysql_;
        },
        Safet:function(char,charu){
            if( (! char || char =="") && char !== 0){
                return "''";
            }
            if(typeof(char) != "string"){
                return char;
            }
            var  Safety = {
                'create ':'crteea',
                'select ':'secelt',
                'update ':'upteda',
                'delete ':'detele',
                'grant ':'gartn',
                'DESCRIBE ':'DESRCIBE',
                'database ':'datbase',
                'show tables':'showw tbales',
                'drop ':'dorp',
                'insert ':'inesrt',
                'alter ':'atler',
                '`':''
            }
            Safety[MYSQLconfig.prefix] =  'DBprefix';
            for(var yuan in Safety){
                char = char.replace(new RegExp(yuan,"igm"),Safety[yuan]);
            }
            if(charu){
                return DB.escape(char);
            }
            return char;

        },ARRint(value){
            let temp =[];
            if(typeof(value) != "object"){
                value = (""+value).split(',');
            }
            for(var ii in value){
                let zhi = value[ii];
                zhi = parseInt(""+zhi)*1;
                temp.push(zhi);
            }
            return temp.join(",");

        },SafeT:function(char){
            if(! char || char ==""){
                return char;
            }
            if(typeof(char) != "string"){
                return char;
            }
            var  Safety = ['>=','>',"\\(","\\)",'<=','<','!=','OLK','LIKE','OR','IN','DAYD','DAY','XIYD','XIY','DEY',' ','=','~','@'];
            for(var yuan in Safety){
                char = char.replace(new RegExp(Safety[yuan],"gm"),"");
            }
            return char;
        
        },Wherezuhe(tian){

            if(count(tian) == 0){
                return "";
            }
            var where = "";
            var table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
            if(!Kuo_Mysql_.Table_ || !table){
                return "";
            }
            for(var $k in  tian){
                let $v = tian[$k];
                let $v_ = $v;
                let $k_ = Kuo_Mysql_.SafeT($k);
                if(typeof(table[$k_]) == "undefined" &&  $k_ != ""){
                    continue ;
                }
                if (typeof($v) == "string") {
                    $v = Kuo_Mysql_.Safet($v,true);
                }
                var qianm = 'and';
                if ($k.indexOf('~') > -1) {
                    qianm = 'OR';
                }
                if ($k.indexOf('>=') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` >=  `+$v;
                }else if ($k.indexOf('>') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` > `+$v;
                }else if ($k.indexOf('(') > -1) {
                    if ($v_ == 'and') $v = 'and';
                    else  $v = 'OR';
                    where += " "+$v+" (";
                }else if ($k.indexOf(')') > -1) {
                    where += " ) ";
                } else if ($k.indexOf('<=') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` <=  `+$v;
                }else if ($k.indexOf('<') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` < `+$v;
                }else if ($k.indexOf('!=') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` != `+$v;
                }else if ($k.indexOf('OLK') > -1) {
                    where += ` OR \``+$k_+`\` LIKE `+$v;
                }else if ($k.indexOf('LIKE') > -1) {
                    where += ` `+qianm+` \``+$k_+`\` LIKE `+$v;
                }else if ($k.indexOf('OR') > -1) {
                    where += ` OR \``+$k_+`\` LIKE `+$v;

                }else if ($k.indexOf('IN') > -1) {
                    if(typeof($v) != "object"){
                        where += ` `+qianm+` \``+$k_+`\` IN(`+Kuo_Mysql_.ARRint(Kuo_Mysql_.Safet($v_))+')';
                    }else{
                        where += ` `+qianm+` \``+$k_+`\` IN(`+Kuo_Mysql_.ARRint($v)+')';
                    }
                }else if ($k.indexOf('DAYD') > -1 && table[$v_]) {
                    where += ` `+qianm+` \``+$k_+`\` >= `+$v_;
                }else if ($k.indexOf('DAY') > -1 && table[$v_]) {
                    where += ` `+qianm+` \``+$k_+`\` > `+$v_;
                }else if ($k.indexOf('XIYD') > -1 && table[$v_]) {
                    where += ` `+qianm+` \``+$k_+`\` <= `+$v_;
                }else if ($k.indexOf('XIY') > -1 && table[$v_]) {
                    where += ` `+qianm+` \``+$k_+`\` < `+$v_;
                }else if ($k.indexOf('DEY') > -1 && table[$v_]) {
                    where += ` `+qianm+` \``+$k_+`\` = `+$v_;
                }else{
                    where += ` `+qianm+` \``+$k_+`\` = `+$v;
                }
            }
            if(where == ""){
                return "";
            }
            where = where.replace(/\( OR /g,"( ");
            where = where.replace(/\( and /g,"( ");
            where = LTrim( Trim(where,' '),'OR');
            where = LTrim( Trim(where,' '),'and');
            if(where != ""){
                return 'WHERE '+ where;
            }
            return '';

        },Find:async () =>{
            let $sql  = `SELECT `+(Kuo_Mysql_.Zhicha_?Kuo_Mysql_.Zhicha_:Kuo_MysqlTABLE.TABLE[Kuo_Mysql_.Table_])+` FROM \``+Kuo_Mysql_.Table_+`\` `+(Kuo_Mysql_.Where_?Kuo_Mysql_.Where_:"") +` `+(Kuo_Mysql_.Order_?Kuo_Mysql_.Order_:"")+` Limit 1;`;
            Kuo_Mysql_.ChuShi();
            if(Kuo_Mysql_.Shiwu_){
                return  $sql+Kuo_Mysql_.ShiWuBiao;
            }
            return new Promise((resolve, reject) => {
                DB.query($sql, function (error, results) { 
                    if(error){
                
                        resolve(false);
                        return false;
                    }
                    if(results.length < 1){
                        resolve(false);
                        return false;
                    }
                    resolve(results.pop());
                    return true;
                });
            });
        
        },Select:async () =>{
            let  $sql  = `SELECT `+(Kuo_Mysql_.Zhicha_?Kuo_Mysql_.Zhicha_:Kuo_MysqlTABLE.TABLE[Kuo_Mysql_.Table_])+` FROM \``+Kuo_Mysql_.Table_+`\` `+(Kuo_Mysql_.Where_?Kuo_Mysql_.Where_:"") +` `+(Kuo_Mysql_.Order_?Kuo_Mysql_.Order_:"")+` `+(Kuo_Mysql_.Limit_?Kuo_Mysql_.Limit_:"")+`;`;
            Kuo_Mysql_.ChuShi();
          
            if(Kuo_Mysql_.Shiwu_){
                return  $sql+Kuo_Mysql_.ShiWuBiao;
            }
            return new Promise((resolve, reject) => {
                DB.query($sql, function (error, results) { 
                    if(error){
                        resolve(false);
                        return false;
                    }
                    if(results.length < 1){
                        resolve(false);
                        return false;
                    }
                    resolve(results);
                    return true;
                });
            });

        },Total:async () =>{

            if(!Kuo_Mysql_.Where_ || Kuo_Mysql_.Where_ == ""){
                let ziduan = "";
                let linshibiao = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_]?Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_]:false;
                if(linshibiao){
                    for(var id in linshibiao){
                        if(linshibiao[id] == "auto_increment"){
                            ziduan = id;
                            break ;
                        }
                    }
                    if(ziduan == ""){
                        for(var id in linshibiao){
                            if(id == "id" || linshibiao[id] == '0'){
                                ziduan = id;
                                break ;
                            }
                        }
                    }
                    if(ziduan != ""){
                        Kuo_Mysql_.Where_ = " WHERE `"+ziduan+"` > 0 "
                    }
                }
            }
            let  $sql  = `SELECT count(1) as count FROM \``+Kuo_Mysql_.Table_+`\` `+(Kuo_Mysql_.Where_?Kuo_Mysql_.Where_:"")+`;`;
            Kuo_Mysql_.ChuShi();
            return new Promise((resolve, reject) => {
                DB.query($sql, function (error, results) { 
                    if(error){
                        resolve(0);
                        return 0;
                    }
                    var shuju = results.pop();
                   
                    resolve(Number(shuju['count']));
                    return Number(shuju['count']);
                });
            });

        },Delete:async () =>{

            let $sql = `DELETE  FROM \``+Kuo_Mysql_.Table_+`\` `+(Kuo_Mysql_.Where_?Kuo_Mysql_.Where_:"") +` `+(Kuo_Mysql_.Order_?Kuo_Mysql_.Order_:"")+` `+(Kuo_Mysql_.Limit_?Kuo_Mysql_.Limit_:"")+`;`;
            Kuo_Mysql_.ChuShi();
            return new Promise((resolve, reject) => {
                DB.query($sql, function (error, results) { 
                    if(error){
                        resolve(false);
                        return false;
                    }
                    if(results.affectedRows > 0){
                        resolve(true);
                        return true;
                    }
                    resolve(false);
                    return false;
                });
            });

        },Insert:async ($data) =>{
            if($data){
                let table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
                if(!table){
                    return false;
                }
            
                Kuo_Mysql_.ChuShi();
                var biao = [];
                var Verc = [];
                for(var k in table){
                    var v = table[k];
                    if(typeof($data[k]) != "undefined"){
                        if(v != "auto_increment"){
                            biao.push('`'+k+'`');
                            Verc.push(Kuo_Mysql_.Safet($data[k],true));
                        }
                    }else{
                        if(v != "auto_increment"){
                            biao.push('`'+k+'`');
                            Verc.push(Kuo_Mysql_.Safet(v,true));
                        }
                    }
                }
            
                var $sql = 'INSERT INTO `'+Kuo_Mysql_.Table_+'` (' +biao.join(',')+ ')VALUES (' +Verc.join(',')+  ');';
                if(Kuo_Mysql_.Shiwu_){
                    return  $sql+Kuo_Mysql_.ShiWuBiao;
                }
               
                return new Promise((resolve, reject) => {
                    DB.query($sql, function (error, results) { 
                       
                        if(error){
                            resolve(false);
                            return false;
                        }
                        if(results.insertId > 0){
                            resolve(results.insertId );
                            return results.insertId ;
                        }
                        if(results.affectedRows > 0){
                            resolve(true );
                            return true;
                        }
                        resolve(false);
                        return false;
                    });
                });

            }
            return false;

        },Qurey:async ($jiegou,$data) =>{

            return new Promise((resolve, reject) => {
                DB.query($jiegou,$data, function (error, results) {
                    if(error){
                       
                        resolve(false);
                        return false;
                    }
                    resolve(results);
                    return true;
                });
            });

        },Query:async ($jiegou,$data) =>{

            return await Kuo_Mysql_.Query($jiegou,$data);

        },Update:async ($data) =>{
            if($data){
                var table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
                if(!table){
                    return false;
                }
                
                var biao = [];
                for(var k in table){
                    if(typeof($data[k]) != "undefined" && table[k] != 'auto_increment' ){
                        biao.push('`'+k+'` = '+Kuo_Mysql_.Safet($data[k],true) );
                    }else if(typeof($data[k+' +']) != "undefined" ){

                        biao.push('`'+k+'` = '+k+'  + '+ Kuo_Mysql_.Safet($data[k+' +'],true) );

                    }else if(typeof($data[k+' -']) != "undefined" ){
                        biao.push('`'+k+'` =  '+k+' - '+Kuo_Mysql_.Safet($data[k+' -'],true) );
                    }
                }

                if(biao.length < 1){
                    return false;
                }
                let $sql = `UPDATE \``+Kuo_Mysql_.Table_+`\` SET `+(biao.join(','))+` `+(Kuo_Mysql_.Where_?Kuo_Mysql_.Where_:"") +` `+(Kuo_Mysql_.Order_?Kuo_Mysql_.Order_:"")+` `+(Kuo_Mysql_.Limit_?Kuo_Mysql_.Limit_:"")+`;`;
                Kuo_Mysql_.ChuShi();
                if(Kuo_Mysql_.Shiwu_){
                    return  $sql+Kuo_Mysql_.ShiWuBiao;
                }

                return new Promise((resolve, reject) => {
                    DB.query($sql, function (error, results) { 
                        if(error){
                            resolve(false);
                            return false;
                        }
                        if(results.affectedRows > 0){
                            resolve(true);
                            return true;
                        }
                        resolve(false);
                        return false;
                    });
                });
            }
            return false;

        },ShiWuZi: (resolve,sql,connection)=>{
            var row = sql.shift();
            if(!row){
                connection.commit(function(error) {
                    if (error) {
                        return connection.rollback(function() {
                            connection.release();
                            resolve(false);
                        });
                    }
                    connection.release();
                    resolve(true);
                });
                return true;
            }
            connection.query(row, function (error, results) { 
                if (error) {
                    return connection.rollback(function() {
                        connection.release();
                        resolve(false);
                    });
                }
                Kuo_Mysql_.ShiWuZi(resolve,sql,connection);
            });

        },ShiWu:async ($sql) =>{
            Kuo_Mysql_.ChuShi();
            Kuo_Mysql_.Shiwu_ = false;
            var sql = $sql.split(Kuo_Mysql_.ShiWuBiao);
            return new Promise((resolve, reject) => {
                DB.getConnection(function(err, connection) {
                    if(err){
                        resolve(false);
                        return false;
                    }
                    connection.beginTransaction(function(err) {
                        if(err){
                            resolve(false);
                            return false;
                        }
                        return Kuo_Mysql_.ShiWuZi(resolve,sql,connection);
                    });
                });  
            });    

        },PaiChu(data){
            if(data  && data != "" ){
                var Zhicha_ = [];
                var table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
                if(typeof(data) == "string"){
                    data =  data.split(",");
                }
                var tichu = {};
                for(var k in data){
                    var v = data[k];
                    tichu[v] = v;
                }
                for(var k in table){
                    if(!tichu[k] ){
                        Zhicha_.push('`'+k+'`');
                    }
                }
                if(Zhicha_.length > 0){
                    Kuo_Mysql_.Zhicha_ =Zhicha_.join(",");
                }
            }
            return Kuo_Mysql_;

        },Zhicha(data){
            return Kuo_Mysql_.ZhiCha(data);
        },ZhiCha(data){
            
            if(data  && data != "" ){
                var Zhicha_ = "";
                var table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
                if(typeof(data) == "string"){
                    data =  data.split(",");
                }
                for(var k in data){
                    var v = data[k];
                    if(typeof(table[v]) != "undefined"){
                        Zhicha_ += '`'+v+'`,';
                    }
                }
                if(Zhicha_ != ""){
                    Kuo_Mysql_.Zhicha_= RTrim( Zhicha_,",");
                }
            }
    
            return Kuo_Mysql_;
        },SetShiwu(blue){
            Kuo_Mysql_.Shiwu_ = blue;
            return Kuo_Mysql_;
        },SetShiWu(blue){
            Kuo_Mysql_.Shiwu_ = blue;
            return Kuo_Mysql_;
        },Order(order){
            let order_  = "";
            if(order != "RAND()"){
                var table = Kuo_MysqlTABLE.TaBle[Kuo_Mysql_.Table_];
                if(typeof(order) =="string"){
                    var chai = order.split(",");
                    order = {};
                    for(var chai_ in chai){
                        var zuhe =  Trim(chai[chai_]," ").split(" ");
                        order[zuhe[0]] = zuhe[1];
                    }
                }

                order_  = "";
                for(var k in order ){
                    if(!order[k]){
                        continue ;
                    }
                    var v = order[k].toLowerCase();
                    if((v == "desc" || v == "asc")  && typeof(table[k])!="undefined" ){
                        order_ += k+' '+v+',';
                    }
                }
                if(order_  != ""){
                    order_ = RTrim( order_,",");
                }

            }else{
                order_ = order;
            }
            if(order_  != ""){
                Kuo_Mysql_.Order_ = ' ORDER BY '+order_;
            }
            return Kuo_Mysql_;
        },Limit(num,page){
        
            if(!num || num == ""){
                return Kuo_Mysql_;
            }
            //数量 页码
            if(typeof(page)=="undefined"){
             
                if(typeof(num)=="string"&&num.indexOf(",")>-1){
                    let caifen = explode(",",num);
                    num =   Mode("Tools").Int(caifen[0]*1);
                    page =  Mode("Tools").Int(caifen[1]*1)-1;
                    if(page < 0){
                        page = 0;
                    }   
                    Kuo_Mysql_.Limit_ = " LIMIT "+(page*num)+","+num;
                }else{
                   
                    Kuo_Mysql_.Limit_ = " LIMIT "+  Mode("Tools").Int(num);
                }  

            }else{
                num =  Mode("Tools").Int(num*1);
                page =  Mode("Tools").Int(page*1)-1;
                if(page < 0){
                    page = 0;
                }   
                Kuo_Mysql_.Limit_ = " LIMIT "+(page*num)+","+num;
            }
            return Kuo_Mysql_;

        },Where(tian){
            if(typeof(tian) == "object"){
                Kuo_Mysql_.Where_ = Kuo_Mysql_.Wherezuhe(tian); 
            }
            return Kuo_Mysql_;
        },Biao(){
            return Kuo_Mysql_.Table_;
        },ChuShi(){

            Kuo_Mysql_.Where_=null,
            Kuo_Mysql_.Order_=null,
            Kuo_Mysql_.Limit_=null,
            Kuo_Mysql_.Zhicha_=null;
            return Kuo_Mysql_;
        },
        Init: async (tabel) =>{
            Kuo_Mysql_.ChuShi();
            Kuo_Mysql_.Table_ = MYSQLconfig.prefix+Kuo_Mysql_.Safet(tabel);
            if(!Kuo_MysqlTABLE.TABLE[Kuo_Mysql_.Table_] ){
                await Kuo_Mysql_.JieGou(Kuo_Mysql_.Table_);
            }
            return Kuo_Mysql_;

        },JieGou:async (tabel) =>{
            /* k v 缓存系统读取数据结构 */
   
            let lsTable_ = MYSQLconfig.prefix+Kuo_Mysql_.Safet(tabel);
            if(Kuo_MysqlTABLE.TABLE[lsTable_]){
                return Kuo_Mysql_;
            }

            return new Promise((resolve, reject) => {
                DB.query('desc `'+tabel+'`;', function (error, results) {      
                    Kuo_MysqlTABLE.TaBle[tabel] = {};
                    Kuo_MysqlTABLE.TABLE[tabel] = {};
                    if(!error){
                        var linshi = [];
                        for(var data in results){
                            var shuju = results[data];
                            Kuo_MysqlTABLE.TaBle[tabel][shuju['Field']] = shuju['Default']?shuju['Default']:shuju['Extra'];
                            linshi.push('`'+shuju['Field']+'`');
                        }
                        Kuo_MysqlTABLE.TABLE[tabel] = linshi.join(',');
                       
                    }
                    
                    resolve(1) 
                });
            });

        },SetTable: async (tabel)=>{
            return  Kuo_Mysql_.Init(tabel);
        },TableList:function(){
            //生成表结构
            DB.query('SHOW TABLES;', function (error, results) {
                if(!error){
                    for(var k in results){
                        var form = results[k];
                        var biao = form[Object.keys(form)[0]];
                        Kuo_Mysql_.JieGou(biao);
                    }
                }
            });
        }
    };
    return Kuo_Mysql_;
});
module.exports = Kuo_Mysql;